<template>
	<view class="flex flex-column">
		<!-- 头部 -->
		<yHeader :current="0" :screenWidth="screenWidth" :isTabs="false" @Tabs="handleTabs"></yHeader>
		<view class="flex justify-center py-4" style="height: 100%">
			<view class="content bg-white border border-grey shadow">
				<el-tabs v-model="activeName">
					<el-tab-pane label="账号登录" name="first">
						<el-form ref="form" label-width="80px">
							<el-input v-model="form.username" placeholder="请输入账号" prefix-icon="el-icon-user-solid"
								class="input—x mt-4"></el-input>
							<el-input type="password" v-model="form.password" placeholder="请输入密码"
								prefix-icon="el-icon-lock" class="input—x mt-4" show-password></el-input>

							<el-checkbox-group v-model="form.client">
								<el-checkbox label="记住密码" name="true" class="input—x mt-4"></el-checkbox>
							</el-checkbox-group>

							<el-button :loading="loading" type="success" @click="Login"
								class="btn bg-success">登录</el-button>
							<p>
								<text @click="Register"> 没有账号?点击注册 </text>
								<text @click="ForgotPassword"> 忘记密码 </text>
							</p>
						</el-form>
						<view class="foot flex align-center">
							<el-checkbox-group @change="Checkbox" v-model="agree">
								<el-checkbox name="true"></el-checkbox>
							</el-checkbox-group>
							<text>
								登录即表示已同意
								<text class="text-success hover"
									@click="handleTabs('/pages/login/User_Service_Agreement')">
									《用户服务协议》</text>
								<text class="text-success hover" @click="handleTabs('/pages/login/User_Authorization')">
									《用户授权协议》
								</text>
								<text class="text-success hover" @click="handleTabs('/pages/login/Privacy_Agreement')">
									《隐私政策》
								</text>
							</text>
						</view>
					</el-tab-pane>
					<el-tab-pane label="短信登录" name="second">
						<el-form ref="form" label-width="0px">
							<el-input v-model="form.username" placeholder="请输入手机号" prefix-icon="el-icon-mobile" class="input—x mt-4">
							</el-input>

							<el-form-item label="" class="input—y mt-4" prop="code">
								<view class="flex">
									<el-input v-model="form.code" placeholder="请输入验证码" prefix-icon="el-icon-lock" class="input—x"></el-input>
									<el-button v-if="time" @click="sendMessage" type="success">获取验证码</el-button>
									<el-button v-else type="success">{{secend}}</el-button>
								</view>
							</el-form-item>

							<el-button :loading="loading" type="success" @click="CheckCode()"
								class="btn bg-success">登录</el-button>

							<p>
								<text @click="Register"> 没有账号?点击注册 </text>
								<text @click="ForgotPassword"> 忘记密码 </text>
							</p>
						</el-form>
						<view class="foot flex align-center">
							<el-checkbox-group v-model="agree">
								<el-checkbox name="true"></el-checkbox>
							</el-checkbox-group>
							<text>
								登录即表示已同意
								<text class="text-success hover"
									@click="handleTabs('/pages/login/User_Service_Agreement')">
									《用户服务协议》</text>
								<text class="text-success hover" @click="handleTabs('/pages/login/User_Authorization')">
									《用户授权协议》
								</text>
								<text class="text-success hover" @click="handleTabs('/pages/login/Privacy_Agreement')">
									《隐私政策》
								</text>
							</text>
						</view>
					</el-tab-pane>
				</el-tabs>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import yHeader from "@/components/yHeader.vue";
	import yFooter from "@/components/yFooter.vue";
	import {
		Message,
		Notification
	} from "element-ui";
	import {
		Login
	} from "@/api/login.js";
	import {
		getInquiryIDOriginal,
		getEditAction,
		RedisAdd,
		isPhoneCode
	} from "@/api/global.js";
	export default {
		components: {
			yHeader,
			yFooter,
		},
		data() {
			return {
				timer: null,
				time: true,
				secend: 60,
				RandomCode: '',
				loading: false,
				screenWidth: uni.getSystemInfoSync().windowWidth,
				ThemeColors: app.globalData.ThemeColors,
				activeName: "first",
				form: {
					username: "", //15146557172
					password: "", //a123456
					client: false,
					url: "/pages/index/index",
					type: "true",
					code:'',
				},
				agree: true,
				back: false,
			};
		},
		onLoad(options) {
			if (options.expire) {
				Notification({
					type: "error",
					title: "登录失败",
					message: "登录已失效！",
				});
				this.back = true;
			}
			const storageObject = uni.getStorageSync("zjl_use");
			const sevenDaysAgo = new Date().getTime() - 7 * 24 * 60 * 60 * 1000;
			if (storageObject.timestamp > sevenDaysAgo) {
				this.form.username = storageObject.use;
				this.form.password = storageObject.password;
				this.form.client = storageObject.client;
			} else {
				// 时间戳小于等于7天，显示数据
				console.log(storageObject);
			}
		},
		methods: {
			//忘记密码
			ForgotPassword() {
				uni.navigateTo({
					url: "/pages/login/forgotpassword",
				});
			},
			handleTabs(url) {
				uni.navigateTo({
					url,
				});
			},
			Register() {
				uni.navigateTo({
					url: "/pages/login/register",
				});
			},
			sendMessage() {
				if (this.form.username == '') {
					Message.error("请先输入正确的手机号再点击发送");
					return
				}
				const reg = /^1[3-9]\d{9}$/
				if (!reg.test(this.form.username)) {
					Message.error("请检查手机号格式是否正确!");
					return
				}
				this.time = false
				this.secend = 60
				this.secend--
				this.timer = setInterval(() => {
					if (this.secend == '01') {
						clearInterval(this.timer)
						this.time = true
						return
					}
					this.secend--
					if (this.secend < 10) {
						this.secend = '0' + this.secend
					}
				}, 1000)
				let code = '';
				for (let i = 0; i < 6; i++) {
					code += parseInt(Math.random() * 10);
				}
				this.RandomCode = code
				uniCloud.callFunction({
					name: 'sendSms', //对应的云函数名
					data: {
						phone: this.form.username,
						data: {
							name: '众菌联',
							code: this.RandomCode, //随机生成的验证码，如123456
							action: '注册', //校验类型为“注册”
							expMinute: '5', //短信的有效期，5分钟
						}
					}
				}).then(res => {
					if (res.success) {
						Message.success("短信已发送");
						this.RedisPush()
					}
				}).catch(msg => {
					console.log(msg)
					Message.error("系统错误!请稍后重试");
				});
			},
			async RedisPush() {
				const res = await RedisAdd({
					data: {
						Key: 'zjl_' + this.form.username,
						Main: JSON.stringify({
							code: this.RandomCode,
							expires_in: parseInt(new Date().getTime() / 1000) + 300
						}),
						Expire: 300,
					}
				})
				console.log(res)
			},
			async CheckCode() {
				if(this.form.code.trim()==''){
					Message({
						type:'error',
						message:'请输入短信验证码'
					})
					return
				}
				if(this.form.code.length<6){
					Message({
						type:'error',
						message:'短信验证码为6位有效数字'
					})
					return
				}
				if (!this.agree) {
					Notification({
						type: "error",
						title: "错误",
						message: "请勾选服务协议！",
					});
					return;
				}
				if (this.form.username.trim() == "" || this.form.password.trim() == "") {
					Notification({
						type: "error",
						title: "错误",
						message: "请输入账号或密码",
					});
					return;
				}
				const res = await isPhoneCode({
					data: {
						Code: this.form.code,
						Phone: this.form.username
					}
				})
				if (res.Status == 'success') {
					this.loading = true
					this.Login2()
				} else {
					Message({
						type: 'error',
						message: '短信验证码错误'
					})
				}
			},
			async Login() {
				const that = this;
				if (!this.agree) {
					Notification({
						type: "error",
						title: "错误",
						message: "请勾选服务协议！",
					});
					return;
				}
				if (this.form.username.trim() == "" || this.form.password.trim() == "") {
					Notification({
						type: "error",
						title: "错误",
						message: "请输入账号或密码",
					});
					return;
				}
				this.loading = true;
				const res = await Login({
					data: this.form,
				});
				if (res.resuit === "ERROR" && res.redirect == "REDIRECT") {
					Notification({
						type: "error",
						title: "登录失败",
						message: "用户名或密码错误！",
					});
					this.loading = false
				} else if (res.redirect === "REDIRECT" && res.contentpath) {
					const storageObject = {
						password: null,
						client: null,
						use: null,
						timestamp: null,
					};
					if (this.form.client) {
						storageObject.password = that.form.password;
						storageObject.client = that.form.client;
						storageObject.use = that.form.username;
						storageObject.timestamp = new Date().getTime();

						uni.setStorageSync("zjl_use", storageObject);
					}
					console.log(res)
					// uni.setStorageSync("token", res.cookies);
					// uni.setStorageSync("enterprise", res.enterprise);
					// uni.setStorageSync("username", decodeURI(res.username));
					// uni.setStorageSync("use", res.use);
					// uni.setStorageSync("authentication", res.authentication);
					// uni.setStorageSync("authenticationType", res.authenticationtype);
					let loginInfo = {
						token:res.cookies,
						enterprise:res.enterprise,
						username:decodeURI(res.username),
						use:res.use,
						authentication:res.authentication,
						authenticationType:res.authenticationtype
					}
					uni.setStorageSync('loginInfo',loginInfo)
					Notification({
						type: "success",
						title: "登录成功"
					});
					this.loading = false;
					if (this.back) {
						uni.navigateBack(-1);
					} else {
						window.location.hash = res.contentpath;
					}
				}
			},
			async Login2() {
				const that = this;
				this.form.phone = true
				const res = await Login({
					data: this.form,
				});
				if (res.resuit === "ERROR" && res.redirect == "REDIRECT") {
					Notification({
						type: "error",
						title: "登录失败",
						message: "用户名或密码错误！",
					});
					this.loading = false
				} else if (res.redirect === "REDIRECT" && res.contentpath) {
					const storageObject = {
						password: null,
						client: null,
						use: null,
						timestamp: null,
					};
					if (this.form.client) {
						storageObject.password = that.form.password;
						storageObject.client = that.form.client;
						storageObject.use = that.form.username;
						storageObject.timestamp = new Date().getTime();

						uni.setStorageSync("zjl_use", storageObject);
					}
					// uni.setStorageSync("token", res.cookies);
					// uni.setStorageSync("enterprise", res.enterprise);
					// uni.setStorageSync("username", decodeURI(res.username));
					// uni.setStorageSync("use", res.use);
					// uni.setStorageSync("authentication", res.authentication);
					// uni.setStorageSync("authenticationType", res.authenticationtype);
					let loginInfo = {
						token:res.cookies,
						enterprise:res.enterprise,
						username:decodeURI(res.username),
						use:res.use,
						authentication:res.authentication,
						authenticationType:res.authenticationtype
					}
					uni.setStorageSync('loginInfo',loginInfo)
					Notification({
						type: "success",
						title: "登录成功"
					});
					this.loading = false;
					if (this.back) {
						uni.navigateBack(-1);
					} else {
						window.location.hash = res.contentpath;
					}
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.hover {
		cursor: pointer;
	}

	.hover :hover {
		text-decoration: underline;
	}

	.content {
		width: 400px;
		height: 426px;
		padding: 10px 30px 16px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: space-around;

		.el-tabs {
			width: 100%;
			height: 100%;
		}

		.btn {
			width: 100%;
			margin-top: 40rpx;
			background-color: #28a745 !important;
		}

		.btn2 {
			width: 230rpx;
		}

		p {
			display: flex;
			margin: 20px 0;
			line-height: 17px;
			font-size: 12px;
			color: #646464;
			justify-content: space-between;

			text {
				cursor: pointer;
			}

			text:hover {
				color: #28a745;
			}
		}

		.foot {
			margin: 10px 0 0 0;

			.el-checkbox {
				margin: 0 5px 0 0;
			}

			font-size: 12px;
			color: #646464;
		}

		/deep/ .el-form-item__content {
			display: flex;
		}
	}
</style>